/**
 * WebGPU Command Serializer
 * 将WebGPU API调用序列化到TypedArray中，模拟微信小游戏Metal方案
 */

const {
    CommandType,
    CommandHeader,
    COMMAND_HEADER_SIZE,
    serializeString,
    DataType
} = require('./webgpu-command-protocol.js');

// Dawn 枚举编码映射表
const LoadOp = {
    'clear': 0x00000001,    // WGPULoadOp_Clear
    'load': 0x00000002      // WGPULoadOp_Load
};

const StoreOp = {
    'store': 0x00000002,    // WGPUStoreOp_Store
    'discard': 0x00000001   // WGPUStoreOp_Discard
};

const CompareFunction = {
    'never': 0x00000001,           // WGPUCompareFunction_Never
    'less': 0x00000002,            // WGPUCompareFunction_Less
    'equal': 0x00000003,           // WGPUCompareFunction_Equal
    'less-equal': 0x00000004,      // WGPUCompareFunction_LessEqual
    'greater': 0x00000005,         // WGPUCompareFunction_Greater
    'not-equal': 0x00000006,       // WGPUCompareFunction_NotEqual
    'greater-equal': 0x00000007,   // WGPUCompareFunction_GreaterEqual
    'always': 0x00000008           // WGPUCompareFunction_Always
};

const StencilOperation = {
    'keep': 0x00000001,            // WGPUStencilOperation_Keep
    'zero': 0x00000002,            // WGPUStencilOperation_Zero
    'replace': 0x00000003,         // WGPUStencilOperation_Replace
    'invert': 0x00000004,          // WGPUStencilOperation_Invert
    'increment-clamp': 0x00000005, // WGPUStencilOperation_IncrementClamp
    'decrement-clamp': 0x00000006, // WGPUStencilOperation_DecrementClamp
    'increment-wrap': 0x00000007,  // WGPUStencilOperation_IncrementWrap
    'decrement-wrap': 0x00000008   // WGPUStencilOperation_DecrementWrap
};

const PrimitiveTopology = {
    'point-list': 0x00000001,      // WGPUPrimitiveTopology_PointList
    'line-list': 0x00000002,       // WGPUPrimitiveTopology_LineList
    'line-strip': 0x00000003,      // WGPUPrimitiveTopology_LineStrip
    'triangle-list': 0x00000004,   // WGPUPrimitiveTopology_TriangleList
    'triangle-strip': 0x00000005   // WGPUPrimitiveTopology_TriangleStrip
};

const FrontFace = {
    'ccw': 0x00000001,             // WGPUFrontFace_CCW
    'cw': 0x00000002               // WGPUFrontFace_CW
};

const CullMode = {
    'none': 0x00000001,            // WGPUCullMode_None
    'front': 0x00000002,           // WGPUCullMode_Front
    'back': 0x00000003             // WGPUCullMode_Back
};

const BlendOperation = {
    'add': 0x00000001,             // WGPUBlendOperation_Add
    'subtract': 0x00000002,        // WGPUBlendOperation_Subtract
    'reverse-subtract': 0x00000003, // WGPUBlendOperation_ReverseSubtract
    'min': 0x00000004,             // WGPUBlendOperation_Min
    'max': 0x00000005              // WGPUBlendOperation_Max
};

const BlendFactor = {
    'zero': 0x00000001,                    // WGPUBlendFactor_Zero
    'one': 0x00000002,                     // WGPUBlendFactor_One
    'src': 0x00000003,                     // WGPUBlendFactor_Src
    'one-minus-src': 0x00000004,           // WGPUBlendFactor_OneMinusSrc
    'src-alpha': 0x00000005,               // WGPUBlendFactor_SrcAlpha
    'one-minus-src-alpha': 0x00000006,     // WGPUBlendFactor_OneMinusSrcAlpha
    'dst': 0x00000007,                     // WGPUBlendFactor_Dst
    'one-minus-dst': 0x00000008,           // WGPUBlendFactor_OneMinusDst
    'dst-alpha': 0x00000009,               // WGPUBlendFactor_DstAlpha
    'one-minus-dst-alpha': 0x0000000A,     // WGPUBlendFactor_OneMinusDstAlpha
    'src-alpha-saturated': 0x0000000B,     // WGPUBlendFactor_SrcAlphaSaturated
    'constant': 0x0000000C,                // WGPUBlendFactor_Constant
    'one-minus-constant': 0x0000000D       // WGPUBlendFactor_OneMinusConstant
};

const AddressMode = {
    'clamp-to-edge': 0x00000001,   // WGPUAddressMode_ClampToEdge
    'repeat': 0x00000002,          // WGPUAddressMode_Repeat
    'mirror-repeat': 0x00000003    // WGPUAddressMode_MirrorRepeat
};

const FilterMode = {
    'nearest': 0x00000001,         // WGPUFilterMode_Nearest
    'linear': 0x00000002           // WGPUFilterMode_Linear
};

const MipmapFilterMode = {
    'nearest': 0x00000001,         // WGPUMipmapFilterMode_Nearest
    'linear': 0x00000002           // WGPUMipmapFilterMode_Linear
};

const TextureFormat = {
    'r8unorm': 0x00000001,
    'r8snorm': 0x00000002,
    'r8uint': 0x00000003,
    'r8sint': 0x00000004,
    'r16uint': 0x00000005,
    'r16sint': 0x00000006,
    'r16float': 0x00000007,
    'rg8unorm': 0x00000008,
    'rg8snorm': 0x00000009,
    'rg8uint': 0x0000000A,
    'rg8sint': 0x0000000B,
    'r32uint': 0x0000000C,
    'r32sint': 0x0000000D,
    'r32float': 0x0000000E,
    'rg16uint': 0x0000000F,
    'rg16sint': 0x00000010,
    'rg16float': 0x00000011,
    'rgba8unorm': 0x00000012,
    'rgba8unorm-srgb': 0x00000013,
    'rgba8snorm': 0x00000014,
    'rgba8uint': 0x00000015,
    'rgba8sint': 0x00000016,
    'bgra8unorm': 0x00000017,
    'bgra8unorm-srgb': 0x00000018,
    'rgb10a2unorm': 0x00000019,
    'rg11b10ufloat': 0x0000001A,
    'rgb9e5ufloat': 0x0000001B,
    'rg32uint': 0x0000001C,
    'rg32sint': 0x0000001D,
    'rg32float': 0x0000001E,
    'rgba16uint': 0x0000001F,
    'rgba16sint': 0x00000020,
    'rgba16float': 0x00000021,
    'rgba32uint': 0x00000022,
    'rgba32sint': 0x00000023,
    'rgba32float': 0x00000024,
    'depth32float': 0x00000025,
    'depth24plus': 0x00000026,
    'depth24plus-stencil8': 0x00000027
};

const BufferBindingType = {
    'uniform': 0x00000001,         // WGPUBufferBindingType_Uniform
    'storage': 0x00000002,         // WGPUBufferBindingType_Storage
    'read-only-storage': 0x00000003 // WGPUBufferBindingType_ReadOnlyStorage
};

const SamplerBindingType = {
    'filtering': 0x00000001,       // WGPUSamplerBindingType_Filtering
    'non-filtering': 0x00000002,   // WGPUSamplerBindingType_NonFiltering
    'comparison': 0x00000003       // WGPUSamplerBindingType_Comparison
};

const TextureSampleType = {
    'float': 0x00000001,           // WGPUTextureSampleType_Float
    'unfilterable-float': 0x00000002, // WGPUTextureSampleType_UnfilterableFloat
    'depth': 0x00000003,           // WGPUTextureSampleType_Depth
    'sint': 0x00000004,            // WGPUTextureSampleType_Sint
    'uint': 0x00000005             // WGPUTextureSampleType_Uint
};

const TextureViewDimension = {
    '1d': 0x00000001,              // WGPUTextureViewDimension_1D
    '2d': 0x00000002,              // WGPUTextureViewDimension_2D
    '2d-array': 0x00000003,        // WGPUTextureViewDimension_2DArray
    'cube': 0x00000004,            // WGPUTextureViewDimension_Cube
    'cube-array': 0x00000005,      // WGPUTextureViewDimension_CubeArray
    '3d': 0x00000006               // WGPUTextureViewDimension_3D
};

const StorageTextureAccess = {
    'write-only': 0x00000001,      // WGPUStorageTextureAccess_WriteOnly
    'read-only': 0x00000002,       // WGPUStorageTextureAccess_ReadOnly
    'read-write': 0x00000003       // WGPUStorageTextureAccess_ReadWrite
};

const TextureAspect = {
    'all': 0x00000001,             // WGPUTextureAspect_All
    'stencil-only': 0x00000002,    // WGPUTextureAspect_StencilOnly
    'depth-only': 0x00000003       // WGPUTextureAspect_DepthOnly
};

const TextureDimension = {
    '1d': 0x00000001,              // WGPUTextureDimension_1D
    '2d': 0x00000002,              // WGPUTextureDimension_2D
    '3d': 0x00000003               // WGPUTextureDimension_3D
};

const IndexFormat = {
    'undefined': 0x00000000,       // WGPUIndexFormat_Undefined
    'uint16': 0x00000001,          // WGPUIndexFormat_Uint16
    'uint32': 0x00000002           // WGPUIndexFormat_Uint32
};

class WebGPUCommandSerializer {
    constructor(initialSize = 1024 * 1024) { // 1MB初始大小
        this.buffer = new ArrayBuffer(initialSize);
        this.offset = 0;
        this.resourceIdCounter = 1;
        this.resourceMap = new Map(); // 映射WebGPU对象到ID
        this.pendingCommands = [];
        this.batchMode = false;
    }
    
    // 获取新的资源ID
    getNextResourceId() {
        return this.resourceIdCounter++;
    }
    
    // 注册资源并返回ID
    registerResource(resource) {
        const id = this.getNextResourceId();
        this.resourceMap.set(resource, id);
        return id;
    }
    
    // 获取资源ID
    getResourceId(resource) {
        return this.resourceMap.get(resource) || 0;
    }
    
    // 确保缓冲区有足够空间
    ensureCapacity(size) {
        if (this.offset + size > this.buffer.byteLength) {
            const newSize = Math.max(this.buffer.byteLength * 2, this.offset + size);
            const newBuffer = new ArrayBuffer(newSize);
            new Uint8Array(newBuffer).set(new Uint8Array(this.buffer));
            this.buffer = newBuffer;
        }
    }
    
    // 写入基础数据类型
    writeUint8(value) {
        this.ensureCapacity(1);
        new DataView(this.buffer).setUint8(this.offset, value);
        this.offset += 1;
    }
    
    writeUint16(value) {
        this.ensureCapacity(2);
        new DataView(this.buffer).setUint16(this.offset, value, true);
        this.offset += 2;
    }
    
    writeUint32(value) {
        this.ensureCapacity(4);
        new DataView(this.buffer).setUint32(this.offset, value, true);
        this.offset += 4;
    }
    
    writeFloat32(value) {
        this.ensureCapacity(4);
        new DataView(this.buffer).setFloat32(this.offset, value, true);
        this.offset += 4;
    }
    
    writeString(str) {
        const encoder = new TextEncoder();
        const bytes = encoder.encode(str);
        this.ensureCapacity(4 + bytes.length);
        this.writeUint32(bytes.length);
        new Uint8Array(this.buffer, this.offset, bytes.length).set(bytes);
        this.offset += bytes.length;
    }
    
    writeBuffer(buffer) {
        this.ensureCapacity(4 + buffer.byteLength);
        this.writeUint32(buffer.byteLength);
        new Uint8Array(this.buffer, this.offset, buffer.byteLength).set(new Uint8Array(buffer));
        this.offset += buffer.byteLength;
    }
    
    // 写入命令头部
    writeCommandHeader(type, size, id = 0, flags = 0) {
        const header = new CommandHeader(type, size, id, flags);
        this.ensureCapacity(COMMAND_HEADER_SIZE);
        this.offset = header.serialize(this.buffer, this.offset);
    }
    
    // 开始批量模式
    startBatch() {
        this.batchMode = true;
        this.writeCommandHeader(CommandType.BATCH_START, COMMAND_HEADER_SIZE);
    }
    
    // 结束批量模式
    endBatch() {
        this.batchMode = false;
        this.writeCommandHeader(CommandType.BATCH_END, COMMAND_HEADER_SIZE);
    }
    
    // 序列化创建缓冲区命令
    serializeCreateBuffer(descriptor) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.CREATE_BUFFER, 0); // 先写头部，稍后更新大小
        
        const id = this.getNextResourceId();
        this.writeUint32(id);
        this.writeUint32(descriptor.size);
        this.writeUint32(descriptor.usage);
        this.writeUint8(descriptor.mappedAtCreation ? 1 : 0);
        
        // 更新命令大小
        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
        
        return id;
    }
    
    // 序列化写入缓冲区命令
    serializeWriteBuffer(bufferId, bufferOffset, data) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.WRITE_BUFFER, 0);
        
        this.writeUint32(bufferId);
        this.writeUint32(bufferOffset);
        this.writeBuffer(data);
        
        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }
    
    // 序列化创建渲染管线命令
    serializeCreateRenderPipeline(descriptor, shaderIds) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.CREATE_RENDER_PIPELINE, 0);
        
        const id = this.getNextResourceId();
        this.writeUint32(id);

        // 写入标签
        this.writeString(descriptor.label || '');

        // 写入管线布局
        if (descriptor.layout) {
            this.writeUint8(1); // hasLayout
            if (typeof descriptor.layout === 'string' && descriptor.layout === 'auto') {
                this.writeUint8(1); // isAutoLayout
            } else {
                this.writeUint8(0); // isAutoLayout
                this.writeUint32(this.getResourceId(descriptor.layout) || 0);
            }
        } else {
            this.writeUint8(0); // hasLayout
        }

        // 写入着色器ID
        this.writeUint32(shaderIds.vertex || 0);
        this.writeUint32(shaderIds.fragment || 0);
        
        // 写入顶点状态
        if (descriptor.vertex) {
            this.writeUint8(1); // hasVertexState

            // 写入顶点着色器入口点
            this.writeString(descriptor.vertex.entryPoint || 'main');

            // 写入常量 (constants)
            const constants = descriptor.vertex.constants || {};
            const constantKeys = Object.keys(constants);
            this.writeUint32(constantKeys.length);
            constantKeys.forEach(key => {
                this.writeString(key);
                this.writeFloat32(constants[key]);
            });

            this.writeUint32(descriptor.vertex.buffers ? descriptor.vertex.buffers.length : 0);
            
            if (descriptor.vertex.buffers) {
                descriptor.vertex.buffers.forEach(buffer => {
                    this.writeUint32(buffer.arrayStride);
                    this.writeUint32(buffer.stepMode === 'vertex' ? 0 : 1);
                    this.writeUint32(buffer.attributes ? buffer.attributes.length : 0);
                    
                    if (buffer.attributes) {
                        buffer.attributes.forEach(attr => {
                            this.writeUint32(TextureFormat[attr.format]);
                            this.writeUint32(attr.offset);
                            this.writeUint32(attr.shaderLocation);
                        });
                    }
                });
            }
        } else {
            this.writeUint8(0); // hasVertexState
        }
        
        // 写入原始状态 (primitive state)
        if (descriptor.primitive) {
            this.writeUint8(1); // hasPrimitiveState
            this.writeUint32(PrimitiveTopology[descriptor.primitive.topology || 'triangle-list']);
            this.writeUint32(IndexFormat[descriptor.primitive.stripIndexFormat || 'undefined']);
            this.writeUint32(FrontFace[descriptor.primitive.frontFace || 'ccw']);
            this.writeUint32(CullMode[descriptor.primitive.cullMode || 'none']);
            this.writeUint8(descriptor.primitive.unclippedDepth ? 1 : 0);
        } else {
            this.writeUint8(0); // hasPrimitiveState
        }

        // 写入深度模板状态 (depth-stencil state)
        if (descriptor.depthStencil) {
            this.writeUint8(1); // hasDepthStencilState
            this.writeUint32(TextureFormat[descriptor.depthStencil.format]);
            this.writeUint8(descriptor.depthStencil.depthWriteEnabled ? 1 : 0);
            this.writeUint32(CompareFunction[descriptor.depthStencil.depthCompare || 'always']);

            // 写入模板前面状态
            if (descriptor.depthStencil.stencilFront) {
                this.writeUint8(1); // hasStencilFront
                this.writeUint32(CompareFunction[descriptor.depthStencil.stencilFront.compare || 'always']);
                this.writeUint32(StencilOperation[descriptor.depthStencil.stencilFront.failOp || 'keep']);
                this.writeUint32(StencilOperation[descriptor.depthStencil.stencilFront.depthFailOp || 'keep']);
                this.writeUint32(StencilOperation[descriptor.depthStencil.stencilFront.passOp || 'keep']);
            } else {
                this.writeUint8(0); // hasStencilFront
            }

            // 写入模板背面状态
            if (descriptor.depthStencil.stencilBack) {
                this.writeUint8(1); // hasStencilBack
                this.writeUint32(CompareFunction[descriptor.depthStencil.stencilBack.compare || 'always']);
                this.writeUint32(StencilOperation[descriptor.depthStencil.stencilBack.failOp || 'keep']);
                this.writeUint32(StencilOperation[descriptor.depthStencil.stencilBack.depthFailOp || 'keep']);
                this.writeUint32(StencilOperation[descriptor.depthStencil.stencilBack.passOp || 'keep']);
            } else {
                this.writeUint8(0); // hasStencilBack
            }

            this.writeUint32(descriptor.depthStencil.stencilReadMask || 0xFFFFFFFF);
            this.writeUint32(descriptor.depthStencil.stencilWriteMask || 0xFFFFFFFF);
            this.writeFloat32(descriptor.depthStencil.depthBias || 0);
            this.writeFloat32(descriptor.depthStencil.depthBiasSlopeScale || 0);
            this.writeFloat32(descriptor.depthStencil.depthBiasClamp || 0);
        } else {
            this.writeUint8(0); // hasDepthStencilState
        }

        // 写入多重采样状态 (multisample state)
        if (descriptor.multisample) {
            this.writeUint8(1); // hasMultisampleState
            this.writeUint32(descriptor.multisample.count || 1);
            this.writeUint32(descriptor.multisample.mask || 0xFFFFFFFF);
            this.writeUint8(descriptor.multisample.alphaToCoverageEnabled ? 1 : 0);
        } else {
            this.writeUint8(0); // hasMultisampleState
        }

        // 写入片段状态 (fragment state)
        if (descriptor.fragment) {
            this.writeUint8(1); // hasFragmentState

            // 写入片段着色器入口点
            this.writeString(descriptor.fragment.entryPoint || 'main');

            // 写入常量 (constants)
            const constants = descriptor.fragment.constants || {};
            const constantKeys = Object.keys(constants);
            this.writeUint32(constantKeys.length);
            constantKeys.forEach(key => {
                this.writeString(key);
                this.writeFloat32(constants[key]);
            });

            this.writeUint32(descriptor.fragment.targets ? descriptor.fragment.targets.length : 0);

            if (descriptor.fragment.targets) {
                descriptor.fragment.targets.forEach(target => {
                    if (target) {
                        this.writeUint8(1); // hasTarget
                        this.writeUint32(TextureFormat[target.format]);

                        // 写入颜色混合状态
                        if (target.blend) {
                            this.writeUint8(1); // hasBlend

                            // 颜色混合
                            if (target.blend.color) {
                                this.writeUint8(1); // hasColorBlend
                                this.writeUint32(BlendOperation[target.blend.color.operation || 'add']);
                                this.writeUint32(BlendFactor[target.blend.color.srcFactor || 'one']);
                                this.writeUint32(BlendFactor[target.blend.color.dstFactor || 'zero']);
                            } else {
                                this.writeUint8(0); // hasColorBlend
                            }

                            // Alpha混合
                            if (target.blend.alpha) {
                                this.writeUint8(1); // hasAlphaBlend
                                this.writeUint32(BlendOperation[target.blend.alpha.operation || 'add']);
                                this.writeUint32(BlendFactor[target.blend.alpha.srcFactor || 'one']);
                                this.writeUint32(BlendFactor[target.blend.alpha.dstFactor || 'zero']);
                            } else {
                                this.writeUint8(0); // hasAlphaBlend
                            }
                        } else {
                            this.writeUint8(0); // hasBlend
                        }

                        this.writeUint32(target.writeMask !== undefined ? target.writeMask : 0xF);
                    } else {
                        this.writeUint8(0); // hasTarget
                    }
                });
            }
        } else {
            this.writeUint8(0); // hasFragmentState
        }
        
        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
        
        return id;
    }
    
    // 序列化绘制命令
    serializeDraw(renderBundleId = null, vertexCount, instanceCount = 1, firstVertex = 0, firstInstance = 0) {
        const startOffset = this.offset;
        // 根据是否是render bundle选择不同的命令类型
        const commandType = renderBundleId !== null ? CommandType.BUNDLE_DRAW : CommandType.DRAW;
        this.writeCommandHeader(commandType, 0);

        // 对于render bundle命令，bundle ID作为第一个参数
        if (renderBundleId !== null) {
            this.writeUint32(renderBundleId);
        }

        this.writeUint32(vertexCount);
        this.writeUint32(instanceCount);
        this.writeUint32(firstVertex);
        this.writeUint32(firstInstance);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }
    
    // 序列化创建着色器模块命令
    serializeCreateShaderModule(descriptor) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.CREATE_SHADER_MODULE, 0);

        const id = this.getNextResourceId();
        this.writeUint32(id);
        this.writeString(descriptor.code);
        this.writeString(descriptor.label || '');

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);

        return id;
    }

    // 序列化创建绑定组布局命令
    serializeCreateBindGroupLayout(descriptor) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.CREATE_BIND_GROUP_LAYOUT, 0);

        const id = this.getNextResourceId();
        this.writeUint32(id);
        this.writeString(descriptor.label || '');

        // 写入绑定条目
        const entries = descriptor.entries || [];
        this.writeUint32(entries.length);

        entries.forEach(entry => {
            this.writeUint32(entry.binding);
            this.writeUint32(entry.visibility);

            // 写入绑定类型
            if (entry.buffer) {
                this.writeUint8(1); // hasBuffer
                this.writeUint32(BufferBindingType[entry.buffer.type || 'uniform']);
                this.writeUint8(entry.buffer.hasDynamicOffset ? 1 : 0);
                this.writeUint32(entry.buffer.minBindingSize || 0);
            } else {
                this.writeUint8(0);
            }

            if (entry.sampler) {
                this.writeUint8(1); // hasSampler
                this.writeUint32(SamplerBindingType[entry.sampler.type || 'filtering']);
            } else {
                this.writeUint8(0);
            }

            if (entry.texture) {
                this.writeUint8(1); // hasTexture
                this.writeUint32(TextureSampleType[entry.texture.sampleType || 'float']);
                this.writeUint32(TextureViewDimension[entry.texture.viewDimension || '2d']);
                this.writeUint8(entry.texture.multisampled ? 1 : 0);
            } else {
                this.writeUint8(0);
            }

            if (entry.storageTexture) {
                this.writeUint8(1); // hasStorageTexture
                this.writeUint32(StorageTextureAccess[entry.storageTexture.access]);
                this.writeUint32(TextureFormat[entry.storageTexture.format]);
                this.writeUint32(TextureViewDimension[entry.storageTexture.viewDimension || '2d']);
            } else {
                this.writeUint8(0);
            }
        });

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);

        return id;
    }

    // 序列化创建绑定组命令
    serializeCreateBindGroup(descriptor) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.CREATE_BIND_GROUP, 0);

        const id = this.getNextResourceId();
        this.writeUint32(id);
        this.writeString(descriptor.label || '');
        this.writeUint32(this.getResourceId(descriptor.layout));

        // 写入绑定条目
        const entries = descriptor.entries || [];
        this.writeUint32(entries.length);

        entries.forEach(entry => {
            this.writeUint32(entry.binding);

            if (entry.resource.buffer !== undefined) {
                this.writeUint8(1); // isBuffer
                this.writeUint32(this.getResourceId(entry.resource.buffer));
                this.writeUint32(entry.resource.offset || 0);
                this.writeUint32(entry.resource.size || 0);
            } else if (entry.resource.arrayBuffer !== undefined) {
                this.writeUint8(2); // isArrayBuffer
                this.writeBuffer(entry.resource.arrayBuffer);
            } else if (entry.resource instanceof GPUTextureView || entry.resource.texture !== undefined) {
                this.writeUint8(3); // isTextureView
                this.writeUint32(this.getResourceId(entry.resource));
            } else if (entry.resource instanceof GPUSampler) {
                this.writeUint8(4); // isSampler
                this.writeUint32(this.getResourceId(entry.resource));
            } else {
                this.writeUint8(0); // unknown
            }
        });

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);

        return id;
    }

    // 序列化创建管线布局命令
    serializeCreatePipelineLayout(descriptor) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.CREATE_PIPELINE_LAYOUT, 0);

        const id = this.getNextResourceId();
        this.writeUint32(id);
        this.writeString(descriptor.label || '');

        // 写入绑定组布局
        const bindGroupLayouts = descriptor.bindGroupLayouts || [];
        this.writeUint32(bindGroupLayouts.length);
        bindGroupLayouts.forEach(layout => {
            this.writeUint32(this.getResourceId(layout));
        });

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);

        return id;
    }

    // 序列化创建纹理命令
    serializeCreateTexture(descriptor) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.CREATE_TEXTURE, 0);

        const id = this.getNextResourceId();
        this.writeUint32(id);
        this.writeString(descriptor.label || '');

        // 写入纹理大小
        const size = descriptor.size;
        if (Array.isArray(size)) {
            this.writeUint32(size[0] || 1);
            this.writeUint32(size[1] || 1);
            this.writeUint32(size[2] || 1);
        } else {
            this.writeUint32(size.width || 1);
            this.writeUint32(size.height || 1);
            this.writeUint32(size.depthOrArrayLayers || 1);
        }

        this.writeUint32(descriptor.mipLevelCount || 1);
        this.writeUint32(descriptor.sampleCount || 1);
        this.writeUint32(TextureDimension[descriptor.dimension || '2d']);
        this.writeUint32(TextureFormat[descriptor.format]);
        this.writeUint32(descriptor.usage);

        // 写入视图格式
        const viewFormats = descriptor.viewFormats || [];
        this.writeUint32(viewFormats.length);
        viewFormats.forEach(format => {
            this.writeUint32(TextureFormat[format]);
        });

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);

        return id;
    }

    // 序列化创建纹理视图命令
    serializeCreateTextureView(textureId, descriptor = {}) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.CREATE_TEXTURE_VIEW, 0);

        const id = this.getNextResourceId();
        this.writeUint32(id);
        this.writeUint32(textureId);
        this.writeString(descriptor.label || '');
        this.writeUint32(descriptor.format ? TextureFormat[descriptor.format] : 0);
        this.writeUint32(descriptor.dimension ? TextureViewDimension[descriptor.dimension] : 0);
        this.writeUint32(TextureAspect[descriptor.aspect || 'all']);
        this.writeUint32(descriptor.baseMipLevel || 0);
        this.writeUint32(descriptor.mipLevelCount || 0);
        this.writeUint32(descriptor.baseArrayLayer || 0);
        this.writeUint32(descriptor.arrayLayerCount || 0);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);

        return id;
    }

    // 序列化创建采样器命令
    serializeCreateSampler(descriptor = {}) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.CREATE_SAMPLER, 0);

        const id = this.getNextResourceId();
        this.writeUint32(id);
        this.writeString(descriptor.label || '');
        this.writeUint32(AddressMode[descriptor.addressModeU || 'clamp-to-edge']);
        this.writeUint32(AddressMode[descriptor.addressModeV || 'clamp-to-edge']);
        this.writeUint32(AddressMode[descriptor.addressModeW || 'clamp-to-edge']);
        this.writeUint32(FilterMode[descriptor.magFilter || 'nearest']);
        this.writeUint32(FilterMode[descriptor.minFilter || 'nearest']);
        this.writeUint32(MipmapFilterMode[descriptor.mipmapFilter || 'nearest']);
        this.writeFloat32(descriptor.lodMinClamp || 0);
        this.writeFloat32(descriptor.lodMaxClamp || 32);
        this.writeUint32(descriptor.compare ? CompareFunction[descriptor.compare] : 0);
        this.writeUint16(descriptor.maxAnisotropy || 1);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);

        return id;
    }

    // 序列化创建计算管线命令
    serializeCreateComputePipeline(descriptor) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.CREATE_COMPUTE_PIPELINE, 0);

        const id = this.getNextResourceId();
        this.writeUint32(id);
        this.writeString(descriptor.label || '');

        // 写入布局
        if (descriptor.layout) {
            this.writeUint8(1); // hasLayout
            if (typeof descriptor.layout === 'string' && descriptor.layout === 'auto') {
                this.writeUint8(1); // isAutoLayout
            } else {
                this.writeUint8(0); // isAutoLayout
                this.writeUint32(this.getResourceId(descriptor.layout) || 0);
            }
        } else {
            this.writeUint8(0); // hasLayout
        }

        // 写入计算着色器
        this.writeUint32(this.getResourceId(descriptor.compute.module));
        this.writeString(descriptor.compute.entryPoint || 'main');

        // 写入常量
        const constants = descriptor.compute.constants || {};
        const constantKeys = Object.keys(constants);
        this.writeUint32(constantKeys.length);
        constantKeys.forEach(key => {
            this.writeString(key);
            this.writeFloat32(constants[key]);
        });

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);

        return id;
    }

    // 序列化写入纹理命令
    serializeWriteTexture(destination, data, dataLayout, size) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.WRITE_TEXTURE, 0);

        // 写入目标纹理信息
        this.writeUint32(this.getResourceId(destination.texture));
        this.writeUint32(destination.mipLevel || 0);

        // 写入原点
        if (destination.origin) {
            this.writeUint32(destination.origin.x || 0);
            this.writeUint32(destination.origin.y || 0);
            this.writeUint32(destination.origin.z || 0);
        } else {
            this.writeUint32(0);
            this.writeUint32(0);
            this.writeUint32(0);
        }

        this.writeUint32(TextureAspect[destination.aspect || 'all']);

        // 写入数据布局
        this.writeUint32(dataLayout.offset || 0);
        this.writeUint32(dataLayout.bytesPerRow || 0);
        this.writeUint32(dataLayout.rowsPerImage || 0);

        // 写入大小
        if (Array.isArray(size)) {
            this.writeUint32(size[0] || 1);
            this.writeUint32(size[1] || 1);
            this.writeUint32(size[2] || 1);
        } else {
            this.writeUint32(size.width || 1);
            this.writeUint32(size.height || 1);
            this.writeUint32(size.depthOrArrayLayers || 1);
        }

        // 写入数据
        this.writeBuffer(data);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化缓冲区拷贝命令
    serializeCopyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.COPY_BUFFER, 0);

        this.writeUint32(this.getResourceId(source));
        this.writeUint32(sourceOffset);
        this.writeUint32(this.getResourceId(destination));
        this.writeUint32(destinationOffset);
        this.writeUint32(size);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化纹理拷贝命令
    serializeCopyTextureToTexture(source, destination, copySize) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.COPY_TEXTURE, 0);

        // 写入源纹理信息
        this.writeUint32(this.getResourceId(source.texture));
        this.writeUint32(source.mipLevel || 0);

        if (source.origin) {
            this.writeUint32(source.origin.x || 0);
            this.writeUint32(source.origin.y || 0);
            this.writeUint32(source.origin.z || 0);
        } else {
            this.writeUint32(0);
            this.writeUint32(0);
            this.writeUint32(0);
        }

        this.writeUint32(TextureAspect[source.aspect || 'all']);

        // 写入目标纹理信息
        this.writeUint32(this.getResourceId(destination.texture));
        this.writeUint32(destination.mipLevel || 0);

        if (destination.origin) {
            this.writeUint32(destination.origin.x || 0);
            this.writeUint32(destination.origin.y || 0);
            this.writeUint32(destination.origin.z || 0);
        } else {
            this.writeUint32(0);
            this.writeUint32(0);
            this.writeUint32(0);
        }

        this.writeUint32(TextureAspect[destination.aspect || 'all']);

        // 写入拷贝大小
        if (Array.isArray(copySize)) {
            this.writeUint32(copySize[0] || 1);
            this.writeUint32(copySize[1] || 1);
            this.writeUint32(copySize[2] || 1);
        } else {
            this.writeUint32(copySize.width || 1);
            this.writeUint32(copySize.height || 1);
            this.writeUint32(copySize.depthOrArrayLayers || 1);
        }

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化开始渲染通道命令
    serializeBeginRenderPass(descriptor) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.BEGIN_RENDER_PASS, 0);

        this.writeString(descriptor.label || '');

        // 写入颜色附件
        const colorAttachments = descriptor.colorAttachments || [];
        this.writeUint32(colorAttachments.length);

        colorAttachments.forEach(attachment => {
            if (attachment) {
                this.writeUint8(1); // hasAttachment
                this.writeUint32(this.getResourceId(attachment.view));

                // 写入resolve target
                if (attachment.resolveTarget) {
                    this.writeUint8(1); // hasResolveTarget
                    this.writeUint32(this.getResourceId(attachment.resolveTarget));
                } else {
                    this.writeUint8(0);
                }

                // 写入clear value
                if (attachment.clearValue) {
                    this.writeUint8(1); // hasClearValue
                    if (Array.isArray(attachment.clearValue)) {
                        this.writeFloat32(attachment.clearValue[0] || 0);
                        this.writeFloat32(attachment.clearValue[1] || 0);
                        this.writeFloat32(attachment.clearValue[2] || 0);
                        this.writeFloat32(attachment.clearValue[3] || 1);
                    } else {
                        this.writeFloat32(attachment.clearValue.r || 0);
                        this.writeFloat32(attachment.clearValue.g || 0);
                        this.writeFloat32(attachment.clearValue.b || 0);
                        this.writeFloat32(attachment.clearValue.a || 1);
                    }
                } else {
                    this.writeUint8(0);
                }

                this.writeUint32(LoadOp[attachment.loadOp || 'clear']);
                this.writeUint32(StoreOp[attachment.storeOp || 'store']);
            } else {
                this.writeUint8(0); // hasAttachment
            }
        });

        // 写入深度模板附件
        if (descriptor.depthStencilAttachment) {
            this.writeUint8(1); // hasDepthStencilAttachment
            const depthAttachment = descriptor.depthStencilAttachment;
            this.writeUint32(this.getResourceId(depthAttachment.view));

            // 深度操作
            this.writeUint32(LoadOp[depthAttachment.depthLoadOp || 'clear']);
            this.writeUint32(StoreOp[depthAttachment.depthStoreOp || 'store']);
            this.writeFloat32(depthAttachment.depthClearValue || 1.0);

            // 模板操作
            this.writeUint32(LoadOp[depthAttachment.stencilLoadOp || 'clear']);
            this.writeUint32(StoreOp[depthAttachment.stencilStoreOp || 'store']);
            this.writeUint32(depthAttachment.stencilClearValue || 0);
        } else {
            this.writeUint8(0);
        }

        // 遮挡查询设置
        if (descriptor.occlusionQuerySet) {
            this.writeUint8(1); // hasOcclusionQuerySet
            this.writeUint32(this.getResourceId(descriptor.occlusionQuerySet));
        } else {
            this.writeUint8(0);
        }

        // 时间戳写入
        const timestampWrites = descriptor.timestampWrites || [];
        this.writeUint32(timestampWrites.length);
        timestampWrites.forEach(write => {
            this.writeUint32(this.getResourceId(write.querySet));
            this.writeUint32(write.queryIndex);
            this.writeString(write.location);
        });

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化结束渲染通道命令
    serializeEndRenderPass() {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.END_RENDER_PASS, 0);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化开始计算通道命令
    serializeBeginComputePass(descriptor = {}) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.BEGIN_COMPUTE_PASS, 0);

        this.writeString(descriptor.label || '');

        // 时间戳写入
        const timestampWrites = descriptor.timestampWrites || [];
        this.writeUint32(timestampWrites.length);
        timestampWrites.forEach(write => {
            this.writeUint32(this.getResourceId(write.querySet));
            this.writeUint32(write.queryIndex);
            this.writeString(write.location);
        });

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化结束计算通道命令
    serializeEndComputePass() {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.END_COMPUTE_PASS, 0);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化设置管线命令
    serializeSetPipeline(renderPassId, pipelineId) {
        const startOffset = this.offset;
        // 根据是否是render bundle选择不同的命令类型
        const commandType = CommandType.SET_PIPELINE;
        this.writeCommandHeader(commandType, 0);

        this.writeUint32(renderPassId);
        this.writeUint32(pipelineId);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // Render Bundle专用的setPipeline方法
    serializeSetPipelineInBundle(pipelineId, bundleId) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.SET_PIPELINE, 0);

        this.writeUint32(pipelineId);
        this.writeUint32(bundleId); // 标记这是render bundle内的命令

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化设置绑定组命令
    serializeSetBindGroup(renderPassId, index, bindGroupId, dynamicOffsets = [], dynamicOffsetsStart = 0, dynamicOffsetsLength = null) {
        const startOffset = this.offset;
        // 根据是否是render bundle选择不同的命令类型
        const commandType = CommandType.SET_BIND_GROUP;
        this.writeCommandHeader(commandType, 0);

        this.writeUint32(renderPassId);
        this.writeUint32(index);
        this.writeUint32(bindGroupId);

        // 直接写入dynamicOffsets，避免类型转换以提高性能
        if (dynamicOffsets) {
            if (dynamicOffsets instanceof Uint32Array) {
                this.writeUint32(dynamicOffsetsLength);
                this.buffer.set(dynamicOffsets.subarray(dynamicOffsetsStart, dynamicOffsetsStart + dynamicOffsetsLength), this.offset)
                this.offset += dynamicOffsetsLength;
            } else if (Array.isArray(dynamicOffsets)) {
                this.writeUint32(dynamicOffsets.length);
                this.buffer.set(dynamicOffsets, this.offset)
                this.offset += dynamicOffsets.length;
            } 
        } else {
            // null或undefined - 空数组
            this.writeUint32(0);
        }

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化设置顶点缓冲区命令
    serializeSetVertexBuffer(renderPassId, slot, bufferId, offset = 0, size = 0) {
        const startOffset = this.offset;
        // 根据是否是render bundle选择不同的命令类型
        const commandType = CommandType.SET_VERTEX_BUFFER;
        this.writeCommandHeader(commandType, 0);

        this.writeUint32(renderPassId);
        this.writeUint32(slot);
        this.writeUint32(bufferId);
        this.writeUint32(offset);
        this.writeUint32(size);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化设置索引缓冲区命令
    serializeSetIndexBuffer(renderPassId, bufferId, format, offset = 0, size = 0) {
        const startOffset = this.offset;
        // 根据是否是render bundle选择不同的命令类型
        const commandType =  CommandType.SET_INDEX_BUFFER;
        this.writeCommandHeader(commandType, 0);

        this.writeUint32(renderPassId);
        this.writeUint32(bufferId);
        // 使用IndexFormat枚举而不是TextureFormat，与Dawn保持一致
        this.writeUint32(format || 0x00000001); // 默认uint16
        this.writeUint32(offset);
        this.writeUint32(size);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化绘制索引命令
    serializeDrawIndexed(renderPassId = null, indexCount, instanceCount = 1, firstIndex = 0, baseVertex = 0, firstInstance = 0) {
        const startOffset = this.offset;
        // 根据是否是render bundle选择不同的命令类型
        const commandType = CommandType.DRAW_INDEXED;
        this.writeCommandHeader(commandType, 0);

        this.writeUint32(renderPassId);
        this.writeUint32(indexCount);
        this.writeUint32(instanceCount);
        this.writeUint32(firstIndex);
        this.writeUint32(baseVertex);
        this.writeUint32(firstInstance);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化调度计算命令
    serializeDispatch(workgroupCountX, workgroupCountY = 1, workgroupCountZ = 1) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.DISPATCH, 0);

        this.writeUint32(workgroupCountX);
        this.writeUint32(workgroupCountY);
        this.writeUint32(workgroupCountZ);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化提交命令
    serializeSubmit(commandBufferIds) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.SUBMIT, 0);

        this.writeUint32(commandBufferIds.length);
        commandBufferIds.forEach(id => {
            this.writeUint32(id);
        });

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化创建命令编码器命令
    serializeCreateCommandEncoder(descriptor = {}) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.CREATE_COMMAND_ENCODER, 0);

        const id = this.getNextResourceId();
        this.writeUint32(id);
        this.writeString(descriptor.label || '');

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);

        return id;
    }

    // 序列化完成命令编码器命令
    serializeFinishCommandEncoder(commandEncoderId, descriptor = {}) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.FINISH_COMMAND_ENCODER, 0);

        const commandBufferId = this.getNextResourceId();
        this.writeUint32(commandBufferId);
        this.writeUint32(commandEncoderId);
        this.writeString(descriptor.label || '');

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);

        return commandBufferId;
    }

    // 序列化创建渲染包编码器命令
    serializeCreateRenderBundleEncoder(descriptor) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.CREATE_RENDER_BUNDLE_ENCODER, 0);

        const id = this.getNextResourceId();
        this.writeUint32(id);
        this.writeString(descriptor.label || '');

        // 写入颜色格式
        const colorFormats = descriptor.colorFormats || [];
        this.writeUint32(colorFormats.length);
        colorFormats.forEach(format => {
            if (format) {
                this.writeUint8(1); // hasFormat
                this.writeUint32(TextureFormat[format]);
            } else {
                this.writeUint8(0); // hasFormat
            }
        });

        // 写入深度模板格式
        if (descriptor.depthStencilFormat) {
            this.writeUint8(1); // hasDepthStencilFormat
            this.writeUint32(TextureFormat[descriptor.depthStencilFormat]);
        } else {
            this.writeUint8(0);
        }

        this.writeUint32(descriptor.sampleCount || 1);
        this.writeUint8(descriptor.depthReadOnly ? 1 : 0);
        this.writeUint8(descriptor.stencilReadOnly ? 1 : 0);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);

        return id;
    }

    // 序列化完成渲染包编码器命令
    serializeFinishRenderBundleEncoder(encoderId, descriptor = {}) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.FINISH_RENDER_BUNDLE_ENCODER, 0);

        const bundleId = this.getNextResourceId();
        this.writeUint32(bundleId);
        this.writeUint32(encoderId);
        this.writeString(descriptor.label || '');

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);

        return bundleId;
    }

    // 序列化执行渲染包命令
    serializeExecuteBundles(renderBundleIds) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.EXECUTE_BUNDLES, 0);

        this.writeUint32(renderBundleIds.length);
        renderBundleIds.forEach(id => {
            this.writeUint32(id);
        });

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化资源销毁命令
    serializeDestroyResource(resourceId, resourceType) {
        const startOffset = this.offset;

        let commandType;
        switch (resourceType) {
            case 'Buffer':
                commandType = CommandType.DESTROY_BUFFER;
                break;
            case 'Texture':
                commandType = CommandType.DESTROY_TEXTURE;
                break;
            case 'RenderPipeline':
                commandType = CommandType.DESTROY_RENDER_PIPELINE;
                break;
            case 'ComputePipeline':
                commandType = CommandType.DESTROY_COMPUTE_PIPELINE;
                break;
            case 'ShaderModule':
                commandType = CommandType.DESTROY_SHADER_MODULE;
                break;
            case 'BindGroupLayout':
                commandType = CommandType.DESTROY_BIND_GROUP_LAYOUT;
                break;
            case 'BindGroup':
                commandType = CommandType.DESTROY_BIND_GROUP;
                break;
            case 'PipelineLayout':
                commandType = CommandType.DESTROY_PIPELINE_LAYOUT;
                break;
            case 'TextureView':
                commandType = CommandType.DESTROY_TEXTURE_VIEW;
                break;
            case 'Sampler':
                commandType = CommandType.DESTROY_SAMPLER;
                break;
            default:
                console.warn('Unknown resource type for destroy:', resourceType);
                return;
        }

        this.writeCommandHeader(commandType, 0);
        this.writeUint32(resourceId);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 获取序列化后的数据
    getSerializedData() {
        return new Uint8Array(this.buffer, 0, this.offset);
    }
    
    // 重置序列化器
    reset() {
        this.offset = 0;
        this.pendingCommands = [];
    }
    
    // 刷新命令到native层
    flush() {
        this.writeCommandHeader(CommandType.FLUSH, COMMAND_HEADER_SIZE);
        const data = this.getSerializedData();
        
        // 这里调用native接口
        if (typeof globalThis.webgpuBatchRender !== 'undefined') {
            globalThis.webgpuBatchRender(data);
        }

        this.reset();
        return data;
    }

    // 序列化设置视口命令
    serializeSetViewport(renderPassId, x, y, width, height, minDepth, maxDepth) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.SET_VIEWPORT, 0);

         this.writeUint32(renderPassId);
        this.writeFloat32(x);
        this.writeFloat32(y);
        this.writeFloat32(width);
        this.writeFloat32(height);
        this.writeFloat32(minDepth);
        this.writeFloat32(maxDepth);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化设置裁剪矩形命令
    serializeSetScissorRect(renderPassId, x, y, width, height) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.SET_SCISSOR_RECT, 0);

        this.writeUint32(renderPassId);
        this.writeUint32(x);
        this.writeUint32(y);
        this.writeUint32(width);
        this.writeUint32(height);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化设置混合常量命令
    serializeSetBlendConstant(renderPassId = null, color) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.SET_BLEND_CONSTANT, 0);

        this.writeUint32(renderPassId);
        

        // 支持color参数可以是对象 {r, g, b, a} 或数组 [r, g, b, a]
        let r, g, b, a;
        if (Array.isArray(color)) {
            // 数组格式：[r, g, b, a]
            [r, g, b, a] = color;
        } else if (color && typeof color === 'object') {
            // 对象格式：{r, g, b, a}
            r = color.r;
            g = color.g;
            b = color.b;
            a = color.a;
        } else {
            // 默认值
            r = g = b = a = 0.0;
        }

        this.writeFloat32(r);
        this.writeFloat32(g);
        this.writeFloat32(b);
        this.writeFloat32(a);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    // 序列化设置模板参考值命令
    serializeSetStencilReference(reference) {
        const startOffset = this.offset;
        this.writeCommandHeader(CommandType.SET_STENCIL_REFERENCE, 0);

        this.writeUint32(renderPassId);
        this.writeUint32(reference);

        const commandSize = this.offset - startOffset;
        new DataView(this.buffer).setUint32(startOffset + 4, commandSize, true);
    }
}

// 导出模块
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        WebGPUCommandSerializer
    };
}